import { useMemo } from 'react';
import { OptionItem, TimeRange } from './type';
import dayjs, { Dayjs, UnitType } from 'dayjs';

const dateUnitConfig: Record<TimeRange, UnitType[]> = {
  day: ['year', 'month', 'date'],
  year: ['year'],
  month: ['year', 'month'],
  'day-time': ['year', 'month', 'date', 'hour', 'minute', 'second'],
  time: ['hour', 'minute', 'second'],
  'hour-minute': ['hour', 'minute'],
  hour: ['hour'],
  minute: ['minute'],
  'minute-second': ['minute', 'second'],
  second: ['second'],
  'day-hour-minute': ['year', 'month', 'date', 'hour', 'minute'],
};
/**
 * 根据时间类型生成options二维数组
 * @param timeRange 选择范围：默认 day年月日
 * @param date 选中的日期, string YYYY-MM-DD之类 */
export const useOptionsByTimeRange = (timeRange: TimeRange, date?: string | Dayjs) => {
  const currentDate = (date ? dayjs(date) : dayjs()).format('YYYY-MM-DD');
  const options = useMemo(() => {
    const list: OptionItem[][] = []; // 生成时分秒到options里
    const dateUnits = dateUnitConfig[timeRange];
    const times: { [key: string]: OptionItem[] } = {
      year: [],
      month: [],
      date: [],
      hour: [],
      minute: [],
      second: [],
    };
    if (!dateUnits) {
      console.warn('useOptionsByTimeRange 异常timeRange', timeRange);
      return list;
    }
    dateUnits.forEach((type: string) => {
      if (type === 'year') {
        const startYear = 1900;
        const endYear = dayjs().year() + 80;
        for (let i = startYear; i < endYear; i++) {
          times.year.push({
            label: `${i}年`,
            value: `${i}`,
          });
        }
      } else if (type === 'month') {
        for (let i = 1; i <= 12; i++) {
          times.month.push({
            label: `${i}月`,
            value: `${i}`,
          });
        }
      } else if (type === 'date') {
        // 根据年月来生成
        for (let i = 1; i <= dayjs(currentDate).daysInMonth(); i++) {
          times.date.push({
            label: `${i}日`,
            value: `${i}`,
          });
        }
      } else if (type === 'hour') {
        for (let i = 0; i < 24; i++) {
          times.hour.push({
            label: `${formatNumWith0(i)}时`,
            value: `${i}`,
          });
        }
      } else if (type === 'minute') {
        for (let i = 0; i < 60; i++) {
          times.minute.push({
            label: `${formatNumWith0(i)}分`,
            value: `${i}`,
          });
        }
      } else if (type === 'second') {
        for (let i = 0; i < 60; i++) {
          times.second.push({
            label: `${formatNumWith0(i)}秒`,
            value: `${i}`,
          });
        }
      }
      list.push(times[type]);
    });
    // console.log('useOptionsByTimeRange options', list, currentDate);
    return list;
  }, [timeRange, currentDate]);

  const defaultSelectedValue = useMemo(() => {
    return dateUnitConfig[timeRange].map((unit, i) => {
      const time = dayjs();
      if (unit === 'year') {
        return time.format('YYYY');
      } else if (unit === 'month') {
        return time.format('M');
      } else if (unit === 'date') {
        return time.format('D');
      } else if (unit === 'hour') {
        return time.format('H');
      } else if (unit === 'minute') {
        return time.format('m');
      } else if (unit === 'second') {
        return time.format('s');
      }
      return options[i][0].value;
    });
  }, [timeRange, options]);

  return { options, defaultSelectedValue };
};

export const getDateByTimeRange = (timeRange: TimeRange, values: string[]) => {
  if (!values?.length) return '';
  const dateUnits = dateUnitConfig[timeRange];
  if (!dateUnits) {
    console.warn('getDateByTimeRange timeRange dateUnits 转化异常', timeRange);
    return;
  }
  let time = dayjs();
  dateUnits.forEach((unit, index) => {
    let num = Number(values[index]);
    if (['month', 'm', 'months'].includes(unit)) num = num - 1;
    if (unit === 'date') {
      console.log('time.daysInMonth()', time.daysInMonth());
    }
    if (unit === 'date' && num > time.daysInMonth()) {
      num = time.daysInMonth();
    }
    time = time.set(unit, num);
    // console.log(unit, num, time.format('YYYY-MM-DD HH:mm:ss'));
  });
  return time.format('YYYY-MM-DD HH:mm:ss');
};

export const formatNumWith0 = (num: number) => {
  if (num < 10) {
    return '0' + num;
  }
  return num;
};
